extends Node
class_name DataTable
#csv文件读取路径
@export var datatable_path = "res://database/"

var datatable_dics:Dictionary = {}

var thread = Thread.new()

signal load_success(table_name:String,data:Array)

func _exit_tree() -> void:
	thread.wait_to_finish()
	
# can_async是否启用线程：异步加载
func load_database(names:PackedStringArray,can_async:bool = true) -> void:
	if can_async:
		thread.start(_load_db.bind(names))
		thread.wait_to_finish()
#		for name in names:
#			var data = res[name]
#			load_success.emit(name,data)
	else:
		_load_db(names)

func  _load_db(table_names:PackedStringArray) -> void:
	for name in table_names:
		var load_result = _load_table(name)
		load_success.emit(name,load_result)
	load_success.emit('finished',[])
#加载数据表
func  _load_table(table_name:String) -> Array:
	var file_path = datatable_path + table_name +".csv"
	assert(FileAccess.file_exists(file_path),'文件不存在')
	var load_result = []
	var file = FileAccess.open(file_path,FileAccess.READ) 
	var data_name = file.get_csv_line() #第一行为数据名称
	var _desc = file.get_csv_line() #第二行数据说明
	var data_type =file.get_csv_line() #第三行为数据类型
	while not file.eof_reached():
		var row_data:PackedStringArray = file.get_csv_line()
		var dic = {}
		for i in row_data.size():
			var d_name:StringName = data_name[i]
			match data_type[i]:
				"int":
					dic[d_name] = int(row_data[i]) if row_data[i] != '' else 0
				"float":
					dic[d_name] = float(row_data[i]) if row_data[i] != '' else 0.0
				"string":
					dic[d_name] = row_data[i]
				"bool":
					dic[d_name] = bool(row_data[i].to_int()) if row_data[i] != '' else true
				"texture":
					if row_data[i].is_empty():
						dic[d_name] = ''
					elif  ResourceLoader.exists(row_data[i]):
						dic[d_name] = ResourceLoader.load(row_data[i]) as Texture
					else:
						assert(false,'加载失败，未知材质数据：'+row_data[i])
				"int[]":
					var res = []
					var tempdata = row_data[i].split("*")
					for k in tempdata:
						res.append(int(k))
					dic[d_name] = res 
				"string[]":
					dic[d_name] = row_data[i].split("*") 
		load_result.append(dic)		
	datatable_dics[table_name] = load_result
	return load_result
